<template>
	<div class="dynamic-table-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<!-- 表格标题和操作 -->
			<div class="table-header mb15">
				<div class="table-title">
					<h3>{{ state.tableConfig.name || configName }}</h3>
					<p v-if="state.tableConfig.description">{{ state.tableConfig.description }}</p>
				</div>
				<div class="table-actions">
					<el-input 
						v-model="state.tableData.param.query" 
						size="default" 
						placeholder="请输入关键词搜索" 
						style="max-width: 200px; margin-right: 10px"
					></el-input>
					<el-button size="default" type="primary" @click="getTableData">
						<el-icon><ele-Search /></el-icon>
						查询
					</el-button>
					<el-button size="default" type="success" @click="onOpenAddDialog">
						<el-icon><ele-Plus /></el-icon>
						新增
					</el-button>
					<el-button size="default" type="info" @click="onRefreshConfig">
						<el-icon><ele-Refresh /></el-icon>
						刷新配置
					</el-button>
				</div>
			</div>

			<!-- 动态表格 -->
			<el-table 
				:data="state.tableData.data" 
				v-loading="state.tableData.loading" 
				style="width: 100%"
				v-if="state.tableConfig.tableFields && state.tableConfig.tableFields.length > 0"
			>
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column
					v-for="field in state.tableConfig.tableFields"
					:key="field.id"
					:prop="field.name"
					:label="field.label"
					:width="field.tableWidth"
					show-overflow-tooltip
				>
					<template #default="scope">
						<span v-if="field.type === 'select' || field.type === 'radio'">
							{{ getOptionLabel(field, scope.row[field.name]) }}
						</span>
						<el-tag 
							v-else-if="field.type === 'checkbox'" 
							v-for="value in (scope.row[field.name] || [])" 
							:key="value"
							size="small"
							class="mr5"
						>
							{{ getOptionLabel(field, value) }}
						</el-tag>
						<span v-else>{{ scope.row[field.name] }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" :width="state.tableConfig.dataPermission ? '280' : '200'" fixed="right">
					<template #default="scope">
						<el-button size="small" text type="primary" @click="onOpenEditDialog(scope.row)">修改</el-button>
						<el-button v-if="state.tableConfig.dataPermission" size="small" text type="success" @click="onOpenPrivilege(scope.row)">授权</el-button>
						<el-button size="small" text type="danger" @click="onRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 空状态 -->
			<div v-else class="empty-config">
				<el-empty description="暂无表格配置，请先配置表格字段" />
			</div>

			<!-- 分页 -->
			<el-pagination
				v-if="state.tableConfig.tableFields && state.tableConfig.tableFields.length > 0"
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30, 50]"
				v-model:current-page="state.tableData.param.page"
			background
			v-model:page-size="state.tableData.param.size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.total"
			>
			</el-pagination>
		</el-card>

		<!-- 数据编辑对话框 -->
		<el-dialog
			v-model="state.dataDialog.isShowDialog"
			:title="state.dataDialog.title"
			width="800px"
			:before-close="onCloseDataDialog"
		>
			<el-form
				ref="dataFormRef"
				:model="state.dataForm"
				:rules="state.formRules"
				label-width="120px"
				size="default"
			>
				<el-row :gutter="20">
					<el-col 
						v-for="field in state.tableConfig.fields" 
						:key="field.id"
						:xs="24" 
						:sm="field.type === 'textarea' ? 24 : 12"
						:md="field.type === 'textarea' ? 24 : 12"
						class="mb20"
					>
						<el-form-item 
							:label="field.label" 
							:prop="field.name"
							:required="field.required"
						>
							<!-- 文本输入 -->
							<el-input
								v-if="field.type === 'text'"
								v-model="state.dataForm[field.name]"
								:placeholder="field.placeholder"
								clearable
							/>
							<!-- 多行文本 -->
							<el-input
								v-else-if="field.type === 'textarea'"
								v-model="state.dataForm[field.name]"
								type="textarea"
								:placeholder="field.placeholder"
								:rows="3"
							/>
							<!-- 数字输入 -->
							<el-input-number
								v-else-if="field.type === 'number'"
								v-model="state.dataForm[field.name]"
								:placeholder="field.placeholder"
								style="width: 100%"
							/>
							<!-- 下拉选择 -->
							<el-select
								v-else-if="field.type === 'select'"
								v-model="state.dataForm[field.name]"
								:placeholder="field.placeholder"
								style="width: 100%"
								clearable
							>
								<el-option
									v-for="option in getFieldOptions(field)"
									:key="option.value"
									:label="option.label"
									:value="option.value"
								/>
							</el-select>
							<!-- 单选框 -->
							<el-radio-group
								v-else-if="field.type === 'radio'"
								v-model="state.dataForm[field.name]"
							>
								<el-radio
									v-for="option in getFieldOptions(field)"
									:key="option.value"
									:label="option.value"
								>
									{{ option.label }}
								</el-radio>
							</el-radio-group>
							<!-- 多选框 -->
							<el-checkbox-group
								v-else-if="field.type === 'checkbox'"
								v-model="state.dataForm[field.name]"
							>
								<el-checkbox
									v-for="option in getFieldOptions(field)"
									:key="option.value"
									:label="option.value"
								>
									{{ option.label }}
								</el-checkbox>
							</el-checkbox-group>
							<!-- 日期选择 -->
							<el-date-picker
								v-else-if="field.type === 'date'"
								v-model="state.dataForm[field.name]"
								type="date"
								:placeholder="field.placeholder"
								style="width: 100%"
							/>
							<!-- 日期时间选择 -->
							<el-date-picker
								v-else-if="field.type === 'datetime'"
								v-model="state.dataForm[field.name]"
								type="datetime"
								:placeholder="field.placeholder"
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<el-button @click="onCloseDataDialog">取消</el-button>
				<el-button type="primary" @click="onSubmitData">{{ state.dataDialog.submitText }}</el-button>
			</template>
		</el-dialog>
		
		<!-- 数据授权对话框 -->
		<PrivilegeDialog ref="privilegeDialogRef" />
	</div>
</template>

<script setup lang="ts" name="dynamicTable">
import { reactive, onMounted, ref, computed } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { tableConfigApi, dynamicTableApi } from '/@/api/tableConfig';
import request from '/@/utils/request';
import PrivilegeDialog from './PrivilegeDialog.vue';

const route = useRoute();
const dataFormRef = ref();
const privilegeDialogRef = ref();

// 从路由获取配置名称
const configName = computed(() => {
	const pathSegments = route.path.split('/');
	return pathSegments[pathSegments.length - 1];
});

// 定义变量内容
const state = reactive({
	tableConfig: {
		id: null,
		name: '',
		dataPermission: false,
		description: '',
		fields: [],
		tableFields: [],
	},
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			query: '',
			page: 1,
			size: 10,
		},
	},
	dataDialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitText: '',
	},
	dataForm: {},
	formRules: {},
	fieldOptions: {}, // 存储各字段的选项数据
});

// 获取表格配置
const getTableConfig = async () => {
	try {
		const res = await tableConfigApi().getConfig({ name: configName.value });
		if (res.code === 0 && res.data) {
			state.tableConfig = res.data;
			// 生成表单验证规则
			generateFormRules();
			// 加载字段选项数据
			await loadFieldOptions();
			// 获取表格数据
			getTableData();
		} else {
			ElMessage.error(res.msg || '未找到对应的表格配置');
		}
	} catch (err: any) {
		console.error('获取表格配置失败:', err);
		ElMessage.error(err.msg || '获取配置失败');
	}
};

// 生成表单验证规则
const generateFormRules = () => {
	const rules: any = {};
	state.tableConfig.fields.forEach((field: any) => {
		if (field.required) {
			rules[field.name] = [
				{ required: true, message: `${field.label}不能为空`, trigger: 'blur' }
			];
		}
	});
	state.formRules = rules;
};

// 加载字段选项数据
const loadFieldOptions = async () => {
	for (const field of state.tableConfig.fields) {
		if (field.optionSource === 'api' && field.apiUrl) {
			try {
				// 使用配置的 API URL 请求数据
				const method = field.apiMethod || 'GET';
				const requestConfig: any = {
					method: method.toUpperCase(),
					url: field.apiUrl,
				};
				
				let data = await request(requestConfig);
				
				// 根据配置的数据路径提取数据
				if (field.apiDataPath) {
					const paths = field.apiDataPath.split('.');
					for (const path of paths) {
						if (data && typeof data === 'object' && path in data) {
							data = data[path];
						} else {
							data = [];
							break;
						}
					}
				}
				
				// 确保数据是数组格式
				if (!Array.isArray(data)) {
					data = [];
				}
				
				// 转换数据格式
				const options = data.map((item: any) => {
					if (typeof item === 'object') {
						return {
							label: item[field.apiLabelField || 'label'] || item.name || item.title,
							value: String(item[field.apiValueField || 'value'] || item.id || item.code) //全部转换成string类型
						};
					} else {
						return {
							label: item,
							value: item
						};
					}
				});
				state.fieldOptions[field.name] = options;
			} catch (err) {
				console.error(`加载字段 ${field.name} 选项失败:`, err);
				state.fieldOptions[field.name] = field.options || [];
			}
		} else {
			state.fieldOptions[field.name] = field.options || [];
		}
	}
};

// 获取字段选项
const getFieldOptions = (field: any) => {
	return state.fieldOptions[field.name] || field.options || [];
};

// 获取选项标签
const getOptionLabel = (field: any, value: any) => {
	const options = getFieldOptions(field);
	const option = options.find((opt: any) => opt.value === value);
	return option ? option.label : value;
};

// 获取表格数据
const getTableData = () => {
	state.tableData.loading = true;
	dynamicTableApi()
		.getTableData(configName.value, state.tableData.param)
		.then((res) => {
			if (res.code === 0) {
				state.tableData.data = res.data.records || [];
				state.tableData.total = res.data.total || 0;
			} else {
				ElMessage.error(res.msg || '获取数据失败');
			}
			setTimeout(() => {
				state.tableData.loading = false;
			}, 300);
		})
		.catch((err) => {
			state.tableData.loading = false;
			ElMessage.error(err.msg || '获取数据失败');
		});
};

// 刷新配置
const onRefreshConfig = () => {
	getTableConfig();
};

// 打开新增对话框
const onOpenAddDialog = () => {
	state.dataDialog.type = 'add';
	state.dataDialog.title = '新增数据';
	state.dataDialog.submitText = '新增';
	
	// 初始化表单数据
	const formData: any = {};
	state.tableConfig.fields.forEach((field: any) => {
		if (field.type === 'checkbox') {
			formData[field.name] = [];
		} else {
			formData[field.name] = field.defaultValue || '';
		}
	});
	state.dataForm = formData;
	state.dataDialog.isShowDialog = true;
};

// 打开编辑对话框
const onOpenEditDialog = (row: any) => {
	state.dataDialog.type = 'edit';
	state.dataDialog.title = '修改数据';
	state.dataDialog.submitText = '修改';
	
	// 复制行数据到表单
	state.dataForm = { ...row };
	state.dataDialog.isShowDialog = true;
};

// 关闭数据对话框
const onCloseDataDialog = () => {
	state.dataDialog.isShowDialog = false;
	state.dataForm = {};
};

// 提交数据
const onSubmitData = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (valid) {
			const apiMethod = state.dataDialog.type === 'add' ? 'addData' : 'updateData';
			dynamicTableApi()[apiMethod](configName.value, state.dataForm)
				.then((res) => {
					if (res.code === 0) {
						getTableData();
						state.dataDialog.isShowDialog = false;
						ElMessage.success('操作成功');
					} else {
						ElMessage.error(res.msg || '操作失败');
					}
				})
				.catch((err) => {
					ElMessage.error(err.msg || '操作失败');
				});
		}
	});
};

// 删除数据
const onRowDel = (row: any) => {
	ElMessageBox.confirm('此操作将永久删除该数据，是否继续?', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			dynamicTableApi()
				.deleteData(configName.value, { id: row.id })
				.then((res) => {
					if (res.code === 0) {
						getTableData();
						ElMessage.success('删除成功');
					} else {
						ElMessage.error(res.msg || '删除失败');
					}
				})
				.catch((err) => {
					ElMessage.error(err.msg || '删除失败');
				});
		})
		.catch(() => {});
};

// 打开数据授权对话框
const onOpenPrivilege = (row: any) => {
	privilegeDialogRef.value.openDialog(state.tableConfig.id, row);
};

// 分页改变
const onHandleSizeChange = (val: number) => {
	state.tableData.param.size = val;
	getTableData();
};

// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableData.param.page = val;
	getTableData();
};

// 页面加载时
onMounted(() => {
	getTableConfig();
});
</script>

<style scoped>
.dynamic-table-container {
	height: 100%;
}

.table-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 16px;
}

.table-title h3 {
	margin: 0 0 8px 0;
	font-size: 18px;
	font-weight: 600;
	color: #303133;
}

.table-title p {
	margin: 0;
	font-size: 14px;
	color: #909399;
}

.table-actions {
	display: flex;
	align-items: center;
}

.empty-config {
	padding: 60px 0;
	text-align: center;
}

.mr5 {
	margin-right: 5px;
}

.mb20 {
	margin-bottom: 20px;
}
</style>